package com.jrx.anytxn.param.service.system.impl;

import com.google.common.collect.Maps;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnException;
import com.jrx.anytxn.common.uitl.BeanMapping;
import com.jrx.anytxn.i18n.context.BaseContextHandler;
import com.jrx.anytxn.param.constant.ErrorMsgConstant;
import com.jrx.anytxn.param.dto.system.CodeTableRes;
import com.jrx.anytxn.param.entity.I18nCore;
import com.jrx.anytxn.param.entity.PrCodeTable;
import com.jrx.anytxn.param.mapper.ext.ExtI18nCoreMapper;
import com.jrx.anytxn.param.mapper.ext.ExtPrCodeTableMapper;
import com.jrx.anytxn.param.service.system.ICodeTableService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Classname CodeTableServiceImpl
 * @Description 代码表
 * @Date 2019/6/13 0013 下午 13:37
 * @author by yf
 */
@Service
@CacheConfig(cacheNames = "CODE_TABLE")
public class CodeTableServiceImpl implements ICodeTableService {

    private static final Logger logger = LoggerFactory.getLogger(CodeTableServiceImpl.class);

    @Resource
    private ExtPrCodeTableMapper extPrCodeTableMapper;
    @Resource
    private ExtI18nCoreMapper extI18nCoreMapper;


    @Override
    public Map<String, List<CodeTableRes>> findMapByTypeIds(List<String> typeIds,String tenantId) throws TxnException {
        if (typeIds.isEmpty()|| StringUtils.isBlank(tenantId)) {
            logger.error("字典类型ID为空");
            throw new TxnException(TxnRespCode.NOT_EMPTY.getCode(), TxnRespCode.NOT_EMPTY.getMsg(ErrorMsgConstant.NO_CODE_LIST_ID));
        }
        HashMap<String, List<CodeTableRes>> codeMap = Maps.newHashMap();
        for (String typeId : typeIds) {
            List<PrCodeTable> sysCodeList = extPrCodeTableMapper.selectAllByTypeIdAndTenId(typeId,tenantId);
            codeMap.put(typeId, BeanMapping.copyList(sysCodeList, CodeTableRes.class));
        }
        return codeMap;
    }

    @Cacheable(key = "'codeTable_'+#tenantId+'_'+#typeId")
    @Override
    public List<PrCodeTable> findListByCodeIds(String typeId, String tenantId) {

        List<PrCodeTable> prCodeTableList = extPrCodeTableMapper.selectByTypeIdAndTenId(typeId,tenantId);
        if(CollectionUtils.isEmpty(prCodeTableList)){
            return Collections.emptyList();
        }
        return prCodeTableList;
    }

    @Cacheable(key = "'codeTable_'+#tenantId+'_'+#typeId+'_'+#codeId")
    @Override
    public PrCodeTable findByTypeAndCodeId(String typeId, String codeId, String tenantId) {
        PrCodeTable prCodeTable = extPrCodeTableMapper.selectByTypeIdAndCodeId(typeId,codeId,tenantId);
        return prCodeTable;
    }
}
